<?php

namespace App\Http\Controllers\Taoke;
use App\Blocks\Goods;
use App\Http\Controllers\Controller;
use App\Libs\Alimama;
use App\Libs\ConvertUrl;
use App\Libs\Jidi;
use App\Libs\Taobao\Taobao;
use App\Models\Category;
use App\Models\ConvertUrls;
use App\Models\Pid;
use App\Models\Product;
use App\Models\User;
use App\Models\UserPid;
use Illuminate\Http\Request;

class GoodsController extends Controller {

    public function getConvertUrl(Request $request){
        $tbid = $request->get('tbid');
        $pid = $request->get('pid', null);
        $converUrlModel = new ConvertUrls();

        $userId = 0;
        $token = $request->get('token', null);
        if($token){
            if($token == 'test123'){
                $userInfo = User::where('id', 1)->first();
            }else {
                $userInfo = \Cache::get($token);
            }

            if($userInfo){
                //是代理获取自己的pid,否则或者上级的,上级也没有就会走默认
                $userId = $userInfo->is_agent?$userInfo->id:$userInfo->father_id;

                $userPidModel = new UserPid();
                $pidModel = new Pid();
                $pidData = \DB::table($userPidModel->getTable() . ' as up')
                    ->select(
                        'p.pid'
                    )
                    ->leftJoin($pidModel->getTable() . ' as p', 'up.pid_id', '=', 'p.id')
                    ->where('up.user_id', $userId)
                    ->first();
                if($pidData){
                    $pid = $pidData->pid;
                }
            }
        }

        \Log::debug($pid);

        $url = ConvertUrls::where('uid', $userId)->where('tbid', $tbid)->first();
        if($url){
            return response()->json($url);
        }

        $converUrlLib = new ConvertUrl();
        $url = $converUrlLib->convertUrl($tbid,null, $pid);

        if(!isset($url['error'])) {
            \DB::table($converUrlModel->getTable())->updateOrInsert([
                'tbid' => $tbid,
                'uid' => $userId
            ], [
                'taosec' => $url['taosec'],
                'url' => $url['url']
            ]);
            return response()->json($url);
        }else{
            return response()->json(['error' => '生成淘口令失败']);
        }

    }

    public function getGoodsList(Request $request){
        $page = $request->get('page',1);
        $length = $request->get('length', 20);
        $offset = ($page - 1) * $length;

        $params = ['cid'];
        $search = [];
        foreach ($params as $param){
            if($request->has($param)){
                $search[$param] = $request->get($param);
            }
        }

        if($request->has('searchKey') && !empty($request->get('searchKey')) && strtolower($request->get('searchKey')) != 'null'){
            $searchKey = $request->get('searchKey');
            $productModel = new Product();
            $data = $productModel->searchEsData($searchKey, $offset, $length);
            if(empty($data['goods'])){
                $aliData = Alimama::getGoodsBySearchKey(['search_key' => $searchKey], $page);
                if(!empty($aliData) && isset($aliData->data->head->status) && $aliData->data->head->status == 'OK') {
                    $goodsData = $aliData->data->pageList;
                    $showGoodsData = [];
                    foreach ($goodsData as $gd) {
                        $showGoodsData[] = [
                            'tbid' => $gd->auctionId,
                            'goods_name' => strip_tags($gd->title),
                            'taobao_title' => strip_tags($gd->title),
                            'goods_pic' => $gd->pictUrl . '_400x400q90.jpg',
                            'quan_fee' => $gd->couponAmount,
                            'sales_price' => $gd->zkPrice,
                            'taoke_price' => $gd->zkPrice - $gd->couponAmount,
                            'sales' => $gd->biz30day,
                            'commission_rate' => $gd->tkRate,
                            'coupon_end' => $gd->couponEffectiveEndTime,
                            'class_id' => $gd->rootCatId,
                            'from' => 'alimama'
                        ];
                    }
                    return response()->json(['current_page' => $page, 'data' => $showGoodsData]);
                }
            } else {
                $taobaoIds = [];
                foreach ($data['goods'] as $goods){
                    $taobaoIds[] = $goods['tbid'];
                }

                $search['tbids'] = $taobaoIds;

                $goodsBlock = new Goods();
                $data = $goodsBlock->getGoodsList($search, 0, $length, 'es');
            }
        }else {
            $goodsBlock = new Goods();
            $data = $goodsBlock->getGoodsList($search, $offset, $length);
        }
        return response()->json(['current_page'=>$page, 'data'=>$data]);
    }

    public function getGoodsInfo($tbid, Request $request)
    {
        $data = [];
        if ($request->has('from') && $request->get('from') == 'alimama') {
            $searchKey = "https://item.taobao.com/item.htm?id=$tbid";
            $page = 1;
            $aliData = Alimama::getGoodsBySearchKey(['search_key' => $searchKey], $page);
            if (!empty($aliData) && isset($aliData->data->head->status) && $aliData->data->head->status == 'OK') {
                $goodsData = $aliData->data->pageList;
                $showGoodsData = [];
                foreach ($goodsData as $gd) {
                    $showGoodsData = [
                        'tbid' => $gd->auctionId,
                        'goods_name' => strip_tags($gd->title),
                        'taobao_title' => strip_tags($gd->title),
                        'goods_pic' => $gd->pictUrl . '_400x400q90.jpg',
                        'quan_fee' => $gd->couponAmount,
                        'sales_price' => $gd->zkPrice,
                        'taoke_price' => $gd->zkPrice - $gd->couponAmount,
                        'sales' => $gd->biz30day,
                        'commission_rate' => $gd->tkRate,
                        'coupon_end' => $gd->couponEffectiveEndTime,
                        'class_id' => $gd->rootCatId,
                        'from' => 'alimama'
                    ];
                }

//                $convertUrlLib = new ConvertUrl();
//                $url = $convertUrlLib->convertUrl($tbid);
//                if(isset($url['error'])){
//                    return ['error'=>$url['error']];
//                }
//                $showGoodsData['coupon_invalid'] = $url['coupon_invalid'];
//                $showGoodsData['url'] = $url['url'];
//                $showGoodsData['taosec'] = $url['taosec'];

                $data = (object)$showGoodsData;
            }
        } else {
            $goodsBlock = new Goods();
            $data = $goodsBlock->getGoodsInfo($tbid);
            $data->coupon_invalid = 0;
            $data->from = 'db';
        }

        return response()->json($data);
    }

    public function getCategoryList(){
        return response()->json(Category::all()->toArray());
    }

    public function share($to, Request $request){
        \Log::debug("share to {$to} url {$request->get('shareLink')}");
    }

    public function search(Request $request){
        $page = $request->get('page',1);
        $length = $request->get('length', 20);
        $offset = ($page - 1) * $length;

        $productModel = new Product();
        $data = $productModel->searchEsData($request->get('search'), $offset, $length);

        return response()->json($data);
    }

    public function test(){
        $taobao = new Taobao();
        dd($taobao->getDgItemCoupon('面膜'));
    }

    public function testESData(){
        $productModel = new Product();

        if($productModel->createEsIndex()) {
            return response()->json(['成功']);
        }
    }
}
